package com.linchong.xshop.web.superadmin.shopadmin;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.linchong.xshop.dto.ImageHolder;
import com.linchong.xshop.dto.ShopExecution;
import com.linchong.xshop.entity.Area;
import com.linchong.xshop.entity.PersonInfo;
import com.linchong.xshop.entity.Shop;
import com.linchong.xshop.entity.ShopCategory;
import com.linchong.xshop.enums.ShopStateEnum;
import com.linchong.xshop.exceptions.ShopOperationException;
import com.linchong.xshop.service.AreaService;
import com.linchong.xshop.service.ProductService;
import com.linchong.xshop.service.ShopCategoryService;
import com.linchong.xshop.service.ShopService;
import com.linchong.xshop.util.CodeUtil;
import com.linchong.xshop.util.HttpServletRequestUtil;
import com.linchong.xshop.util.ImageUtil;
import com.linchong.xshop.util.PathUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author linchong
 * @desc 实现店铺管理的相关逻辑
 * @email littlexbear@163.com
 * @create 2018-07-15 10:19
 * @CopyRight(C) https://blog.csdn.net/littlexbear
 **/

@Controller
@RequestMapping(value = "/shopadmin")
public class ShopManagementController {


    @Autowired
    private ShopService shopService;

    @Autowired
    private ShopCategoryService shopCategoryService;
    @Autowired
    private AreaService areaService;



    @RequestMapping(value = "/getshopmanagementinfo",method = RequestMethod.GET)
    @ResponseBody
    private  Map<String,Object> getShopManagementInfo(HttpServletRequest request){
        Map<String,Object> modelMap = new HashMap<String,Object>();
        long shopId = HttpServletRequestUtil.getLong(request,"shopId");
        if(shopId <= 0){
            Object currentShopObj = request.getSession().getAttribute("currentShop");
            if(currentShopObj == null){
                modelMap.put("redirect",true);
                modelMap.put("url","/xshop/shopadmin/shoplist");
            }else{
                Shop currentShop = (Shop) currentShopObj;
                modelMap.put("redirect",false);
                modelMap.put("shopId",currentShop.getShopId());
            }
        }else {
            logger.info("=================當前店鋪的编号为=================="+shopId);
            Shop currentShop = new Shop();
            currentShop.setShopId(shopId);
            request.getSession().setAttribute("currentShop",currentShop);
            modelMap.put("redirect",false);
    }
        return modelMap;
    }

    //获取店铺列表
    @RequestMapping(value = "/getshoplist",method = RequestMethod.GET)
    @ResponseBody
    private  Map<String,Object> getShopList(HttpServletRequest request){
        Map<String,Object> modelMap = new HashMap<String,Object>();

        PersonInfo user = new PersonInfo();
        user.setUserId(8L);
        user.setName("张三");
        request.getSession().setAttribute("user",user);
        user = (PersonInfo) request.getSession().getAttribute("user");


        try {
            Shop shopCondition = new Shop();
            shopCondition.setOwner(user);

            ShopExecution se = shopService.getShopList(shopCondition,0,100);
            modelMap.put("shopList",se.getShopList());
            modelMap.put("user",user);
            modelMap.put("success",true);
        }catch (Exception e){
            modelMap.put("success",false);
            modelMap.put("errMsg",e.getMessage());
        }
        return modelMap;
    }

    @RequestMapping(value="/getshopbyid",method = RequestMethod.GET)
    @ResponseBody
    private Map<String,Object> getShopById(HttpServletRequest request){

        Map<String,Object> modelMap = new HashMap<String,Object>();
        Long shopId = HttpServletRequestUtil.getLong(request,"shopId");
        if(shopId>-1){
            try{

                Shop shop = shopService.getByShopId(shopId);
                List<Area> areaList = areaService.getAreaList();
                modelMap.put("shop",shop);
                modelMap.put("areaList",areaList);
                modelMap.put("success",true);
            }catch (Exception e){
                modelMap.put("success",false);
                modelMap.put("errMsg",e.toString());
            }
        }else {
            modelMap.put("success",false);
            modelMap.put("errMsg","empty shopId");
        }
        return modelMap;
    }

    Logger logger = LoggerFactory.getLogger(ShopManagementController.class);
    @RequestMapping(value = "/getshopinitinfo",method = RequestMethod.GET)
    @ResponseBody
    private Map<String,Object> getShopInitInfo(){

       logger.info("=====================执行了目标方法==========================");
        Map<String,Object> modelMap = new HashMap<String,Object>();
       List<ShopCategory> shopCategoryList = new ArrayList<ShopCategory>();
       List<Area> areaList = new ArrayList<Area>();
       try{
           shopCategoryList= shopCategoryService.getShopCategoryList(new ShopCategory());
           areaList = areaService.getAreaList();
           modelMap.put("shopCategoryList",shopCategoryList);
           modelMap.put("areaList",areaList);
           modelMap.put("success",true);
       }catch (Exception e){
            modelMap.put("success",false);
            modelMap.put("errMg",e.getMessage());
       }
       return modelMap;
    }

    @RequestMapping(value="/modifyshop",method = RequestMethod.POST)
    @ResponseBody
    private Map<String,Object> modifyShop(HttpServletRequest request){
        Map<String,Object> modelMap = new HashMap<String,Object>();
        if(!CodeUtil.checkVerifyCode(request)){
            modelMap.put("success",false);
            modelMap.put("errMsg","输入了错误的验证码");
            return modelMap;
        }

        //1.接收前端传递来的信息并转化相应的参数，包括店铺信息以及图片信息
        String shopStr = HttpServletRequestUtil.getString(request,"shopStr");
        ObjectMapper mapper = new ObjectMapper();
        Shop shop = null;
        try{
            shop = mapper.readValue(shopStr,Shop.class);
        }catch (Exception e){
            modelMap.put("success",false);
            modelMap.put("errMsg",e.toString());
            return modelMap;
        }
        //处理图片相关信息//接收图片
        CommonsMultipartFile shopImg = null;
        //文件上传解析器，解析request中的文件信息
        CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        //Logger logger = LoggerFactory.getLogger(ShopManagementController.class);
        //判断有没有上传的文件流，如果有，做转换
        if(commonsMultipartResolver.isMultipart(request)){
            MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
            shopImg = (CommonsMultipartFile) multipartHttpServletRequest.getFile("shopImg");
        }

        //2.修改店铺信息

        if(shop!=null&&shop.getShopId()!=null){

            ShopExecution se ;
            try {
                if(shopImg==null){
                    se=shopService.modifyShop(shop,null);
                }else{
                    ImageHolder imageHolder = new ImageHolder(shopImg.getOriginalFilename(),shopImg.getInputStream());
                    se = shopService.modifyShop(shop,imageHolder);
                }

                if(se.getState()== ShopStateEnum.SUCCESS.getState()){
                    modelMap.put("success",true);

                }else {
                    modelMap.put("success",false);
                    modelMap.put("errMsg",se.getStateInfo());
                }

            } catch (ShopOperationException e) {
                modelMap.put("success",false);
                modelMap.put("errMsg",e.getMessage());
            }catch (IOException e){
                modelMap.put("success",false);
                modelMap.put("errMsg",e.getMessage());
            }



            return modelMap;
        }else{
            modelMap.put("success",false);
            modelMap.put("errMsg","请输入店铺信息！");
            return modelMap;
        }
        //3.返回结果

    }



    /**
     *注册店铺
     * @param request
     * @return
     */
    /**
     * 客户通过Http访问服务器，
     * request中存放客户端的所有请求信息
     * 这里是指：客户注册时填表单，通过request获得到用户填写的表单的所有信息
     * 返回值为Map类型的，用来返回一些必要的键值对结果
     *
     * 实现逻辑：
     * 1.接收并转化相应的参数，包括店铺信息以及处理图片
     * 2.注册店铺
     * 3.返回结果
     * */
    @RequestMapping(value="/registershop",method = RequestMethod.POST)
    @ResponseBody
    private Map<String,Object> registerShop(HttpServletRequest request){
        Map<String,Object> modelMap = new HashMap<String,Object>();
        if(!CodeUtil.checkVerifyCode(request)){
            modelMap.put("success",false);
            modelMap.put("errMsg","输入了错误的验证码");
            return modelMap;
        }

        //1.接收前端传递来的信息并转化相应的参数，包括店铺信息以及图片信息
        String shopStr = HttpServletRequestUtil.getString(request,"shopStr");
        ObjectMapper mapper = new ObjectMapper();
        Shop shop = null;
        try{
            shop = mapper.readValue(shopStr,Shop.class);
        }catch (Exception e){
            modelMap.put("success",false);
            modelMap.put("errMsg",e.toString());
            return modelMap;
        }
        //处理图片相关信息//接收图片
        CommonsMultipartFile shopImg = null;
        //文件上传解析器，解析request中的文件信息
        CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        //Logger logger = LoggerFactory.getLogger(ShopManagementController.class);
        //判断有没有上传的文件流，如果有，做转换
        if(commonsMultipartResolver.isMultipart(request)){
            MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
            shopImg = (CommonsMultipartFile) multipartHttpServletRequest.getFile("shopImg");
        }else {
            modelMap.put("success",false);
            modelMap.put("errMsg","上传文件不能为空！");
            return modelMap;
        }

        //2.注册店铺

        if(shop!=null&&shopImg!=null){
            //PersonInfo owner = new PersonInfo();
            //Session TODO：获取用户的信息
            PersonInfo owner = (PersonInfo)request.getSession().getAttribute("user");
            //owner.setUserId(1L);
            shop.setOwner(owner);

            ShopExecution se = null;
            try {

                ImageHolder imageHolder = new ImageHolder(shopImg.getOriginalFilename(),shopImg.getInputStream());
                se = shopService.addShop(shop,imageHolder);

                if(se.getState()== ShopStateEnum.CHENCK.getState()){
                    modelMap.put("success",true);
                    //一对多关系，存储用户可以操作的店铺列表即只有他创建的，才有权限操作
                    //该用户可以操作的店铺列表
                    List<Shop> shopList = (List<Shop>)request.getSession().getAttribute("shopList");
                    //判断，如果是第一次创建店铺，创建出来shopList,将信息存入
                    if(shopList==null||shopList.size()==0){
                        shopList = new ArrayList<Shop>();
                    }
                    shopList.add(se.getShop());
                    request.getSession().setAttribute("shopList",shopList);

                }else {
                    modelMap.put("success",false);
                    modelMap.put("errMsg",se.getStateInfo());
                }

            } catch (ShopOperationException e) {
                modelMap.put("success",false);
                modelMap.put("errMsg",e.getMessage());
            }catch (IOException e){
                modelMap.put("success",false);
                modelMap.put("errMsg",e.getMessage());
            }



            return modelMap;
        }else{
            modelMap.put("success",false);
            modelMap.put("errMsg","请输入店铺信息！");
            return modelMap;
        }
        //3.返回结果

    }

//    private static void inputStreamToFile(InputStream ins,File file){
//
//        FileOutputStream os = null;
//        try{
//            os= new FileOutputStream(file);
//            int byteRead = 0;
//            byte[] buffer = new byte[1024];
//            while((byteRead=ins.read(buffer))!= -1){
//               os.write(buffer,0,byteRead);
//            }
//        }catch (Exception e){
//            throw  new RuntimeException("调用inputStreamToFile出现异常，原因："+e.getMessage());
//        }finally {
//            try{
//                if(os!=null){
//                    os.close();
//                }
//                if(ins!=null){
//                    ins.close();
//                }
//            }catch (IOException e){
//                throw  new RuntimeException("inputStreamToFile关闭IO出现异常，原因："+e.getMessage());
//            }
//        }
//    }


}
